<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!--
Copyright (c) 2013 Mihail Volkov

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<head>
<title>Hatul Madan Sample: Test Console</title>
<style type="text/css">
html, body {
	height: 100%;
	width: 100%;
	margin: 0;
}
table {
	border:0px; /* border="0" */
	border-collapse:collapse; /* cellspacing="0" */
}
.wrapper {
	display: table;
	height: 100%;
	width: 100%;
	background: yellow;
}
.header {
	display: table-row;
	background: gray;
}
.content {
	display: table-row;  /* height is dynamic, and will expand... */
	height: 100%;        /* ...as content is added (won't scroll) */
	max-height: 100%;
	background: black;
	color: green
}
.hatulClient { color: #00FF00 }
.footer {
	display: table-row;
	background: lightgray;
}
.nowrap {
	white-space: nowrap
}
.hspacer {
	width: 4px
}
</style>
<script src="components/date.format.js"></script>
</head>

<body> 

<div class="wrapper">
	<!--
    <div class="header">
A sort of header
    </div>
    -->
    <div class="content">
    	<div style="position: relative; width: 100%; height: 100%">
		    <div id="logScroll" style="position: absolute; top: 0; left: 0; bottom: 0; right: 0; overflow: auto">
		    <div id="log">
		    </div>
		    </div>
	    </div>
    </div>
    <div class="footer">
    <div id="indicators"></div>
<!--Footer of variable height-->
	<table width=100%><tr>
	<td><input id="commandInput" style="width: 100%"></td>
	<td width=1 fixed style="white-space: nowrap">
	<button id="enterButton" type="button">Enter</button>
	<button id="clearButton" type="button">Clear</button>
	<button id="closeButton" type="button" style="display: none">Close</button>
	</td>
	</tr></table>
	<!--<a href="sub/test.html">Test</a>-->
    </div>
</div>
</body>

<script>
//
// Server commands are messages in format STREAM_NAME:the rest of message,
// they are to be printed as such.
// Client commands are posted to the server verbatim, except for /on and /off
// commands that are preprocessed here.
// test_console.streams.json is used for persistence of streams state.
//

var
	commandInput = document.getElementById ("commandInput"),
	logScroll = document.getElementById ("logScroll"),
	log = document.getElementById ("log");

var streamsEnabled = {},
	fileStreams = htmdUnit.openFile ("test_console.streams.json","rt");

if (fileStreams!=null)
{
	var streamsText = fileStreams.readAllText ();
	fileStreams.close ();
	streamsEnabled = JSON.parse (streamsText);
}

// clear log
function clearLog ()
{
	log.innerHTML = "";
}

function appendToLog (str)
{
	var strParsed = str.match (/^([^:]*):([\s\S]*)$/),
		stream = strParsed[1],
		text = strParsed[2],
		isHatulClient = stream=='HATUL_CLIENT';

	var div = document.createElement ('div'),
		spanStream = document.createElement ('span'),
		spanText = document.createElement ('span');
	spanStream.appendChild (document.createTextNode (stream));
	spanText.appendChild (document.createTextNode (text));
	div.innerHTML =
		"<table"+(isHatulClient? " class=hatulClient" : "")
		+"><tr><td width=1 class=nowrap valign=top>"
		+(new Date ()).format ("HH:MM:ss")
		+"</td><td class=hspacer></td><td valign=top>&lt;"
		+"<font color="+(isHatulClient? "white" : "#C0C0C0")+">"+spanStream.innerHTML+"</font>"
		+"&gt; "
		+spanText.innerHTML.replace (/\n/g,"<br>\n")
		+"</td></tr></table>";
	// ^createTextNode escapes html
	log.appendChild (div);
	logScroll.scrollTop = logScroll.scrollHeight;
}

// post command
function postCommand (cmd)
{
	var command = typeof (cmd)!='string'?
		commandInput.value.trim () : cmd.trim ();

	if (command!="")
	{
		// check if it's an on/off cmd
		var commandParsed = command.match (/^(\S+)\s*(\S*)/);

		if (commandParsed[1]=='/on' || commandParsed[1]=='/off')
		{
			var stream = commandParsed[2];
			streamsEnabled[stream] =
				(commandParsed[1]=='/on');
			htmdUnit.postClientCommand
				(commandParsed[1]+" "+stream);
			appendToLog ('HATUL_CLIENT:Log stream '+stream+
				(streamsEnabled[stream]? ' enabled' : ' disabled'));
			fileStreams = htmdUnit.openFile ("test_console.streams.json","wt");
			if (fileStreams!=null)
			{
				fileStreams.writeText (JSON.stringify
					(streamsEnabled,undefined,"\t"));
				fileStreams.close ();
			}
		}
		else
		{
			htmdUnit.postClientCommand (command);
			appendToLog ('HATUL_CLIENT:'+command);
		}
		if (typeof (cmd)!='string')
			commandInput.value = "";
	}
	if (cmd===undefined)
	commandInput.focus ();
}

function postPreConfig ()
{
	// restore enabled/disabled streams state
	for (var stream in streamsEnabled)
	if (streamsEnabled[stream])
		htmdUnit.postClientCommand ("/on "+stream);
	else
		htmdUnit.postClientCommand ("/off "+stream);
}

// handle command from the app
function appCommandReceived (appCmd)
{
	appCmd = appCmd.trim ();
	if (appCmd!="") appendToLog (appCmd);
}

// handle disconnect
function disconnected ()
{
	appendToLog ("HATUL_CLIENT:** connection closed **");
}

// handle re-connect
function reopened ()
{
	appendToLog ("HATUL_CLIENT:** connection restored **");
	postPreConfig ();
	htmdUnit.turnIn ();
}

// setup inputs and event reactions
commandInput.focus ();
commandInput.onkeypress =
	function (evt) { if (evt.keyCode==13) postCommand (); };
document.getElementById ("enterButton").onclick = postCommand;
document.getElementById ("clearButton").onclick = clearLog;
document.getElementById ("closeButton").onclick = function ()
{
	htmdUnit.beginClose ();
};

htmdUnit.disconnected.connect (disconnected);
htmdUnit.reopened.connect (reopened);
htmdUnit.appCommandReceived.connect (appCommandReceived);
postPreConfig ();

// we're ready...
htmdUnit.turnIn ();

</script>

</html>